/*
 * DocumentDestination.java
 *
 * Created on July 17, 2003, 10:00 PM
 */

package org.infoset.xml.util;

import org.infoset.xml.*;

/**
 *
 * @author  alex
 */
public class DocumentDestination implements ItemDestination {
   
   Document result;
   Parent current;

   /** Creates a new instance of DocumentDestination */
   public DocumentDestination() {
      result = null;
      current = null;
   }

   public void send(Item item) 
      throws XMLException
   {
      switch (item.getType()) {
         case DocumentItem:
            result = (Document)item;
            current = (Parent)item;
         break;
         case DocumentEndItem:
            onDocument();
         break;
         case ElementItem:
            if (current==null) {
               result = item.getInfoset().createItemConstructor().createDocument(((Element)item).getBaseURI());
               current = result;
            }
            current.add((Child)item);
            current = (Parent)item;
         break;
         case ElementEndItem:
         {
            ElementEnd end = (ElementEnd)item;
            ((Element)current).setValidity(end.getValidity(),end.getValidationAttempted());
            current = current.getOrigin();
            if (current==null) {
               throw new XMLException("Internal error: origin is null.");
            }
         }
         break;
         case CharactersItem:
         case CommentItem:
         case ProcessingInstructionItem:
            if (current!=null) {
               current.add((Child)item);
            }
         break;
      }
   }
   
   public void onDocument() 
      throws XMLException
   {

   }

   public Document getDocument() {
      return result;
   }
   
   public static Document toDocument(ItemSource source) 
      throws XMLException
   {
      DocumentDestination dest = new DocumentDestination();
      source.copyTo(dest);
      return dest.getDocument();
   }
   
}
